/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cersoft.xmascharity.web;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import org.apache.commons.io.FilenameUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;
import com.cersoft.xmascharity.ejb.ChildFacade;
import com.cersoft.xmascharity.ejb.FamilyFacade;
import com.cersoft.xmascharity.ejb.ImageFacadeREST;
import com.cersoft.xmascharity.ejb.PaymentFacade;
import com.cersoft.xmascharity.entity.Child;
import com.cersoft.xmascharity.entity.Family;
import com.cersoft.xmascharity.entity.Image;
import com.cersoft.xmascharity.entity.Payment;
import java.io.FilenameFilter;
import java.util.Arrays;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

/**
 *
 * @author pbo
 */
@ManagedBean
@ApplicationScoped
public class PboManagedBean {

    @EJB
    private PaymentFacade paymentFacade;
    @EJB
    private ImageFacadeREST imageFacadeREST;
    @EJB
    private ChildFacade childFacade;
    @EJB
    private FamilyFacade familyFacade;
    private String message;
    private Child currChild;
    private Family currFamily;
    
    private List<Child> list1;
    private List<Child> list2;

    public List<Child> getList1() {
        return childFacade.getChildren(currFamily);
    }

    public void setList1(List<Child> list1) {
        this.list1 = list1;
    }

    public List<Child> getList2() {
        return childFacade.getChildrenCriteriaAPI(currFamily);
    }

    public void setList2(List<Child> list2) {
        this.list2 = list2;
    }

    public Family getCurrFamily() {
        return currFamily;
    }

    public String CF(Family f) {
        setCurrFamily(f);
        return "newTemplateClient";
    }
    
    public void setCurrFamily(Family currFamily) {
        this.currFamily = currFamily;
    }
    private Image currImage;
    private List<String> files;
    private String path;

    public List<String> getFiles() {
        File d = new File(path);
        ArrayList<String> res = new ArrayList<String>();
        for (File f : d.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".html");
            }
        })) {
            String s = null;
            try {
                s = f.getName().substring(0,f.getName().indexOf("."));
                String s1 = s.substring(0,s.indexOf("-"));
                String s2 = s.substring(1+s.indexOf("-"));
                s = s1+":"+s2;
            } catch (Exception e) {
            }
            if (s != null && !s.isEmpty()) {
                res.add(s);
            }
        }

        return res;
    }

    public void setFiles(List<String> files) {
        this.files = files;
    }
    private UploadedFile uploadedFile;

    public UploadedFile getUploadedFile() {
        return uploadedFile;
    }

    public void setUploadedFile(UploadedFile uploadedFile) {
        this.uploadedFile = uploadedFile;
    }
    private int newPaymentAmount;
    private String newPaymentEmail;

    public String getNewPaymentEmail() {
        return newPaymentEmail;
    }

    public void setNewPaymentEmail(String newPayment) {
        this.newPaymentEmail = newPayment;
    }

    public int getNewPaymentAmount() {
        return newPaymentAmount;
    }

    public void setNewPaymentAmount(int newPaymentAmount) {
        this.newPaymentAmount = newPaymentAmount;
    }

    public void addPayment() throws Exception {
        Payment payment = new Payment();
        payment.setAmount(newPaymentAmount);
        payment.setEmail(newPaymentEmail);
        paymentFacade.create(payment);

        try {
            String fileName = FilenameUtils.getName(uploadedFile.getName());
            String contentType = uploadedFile.getContentType();
            byte[] bytes = uploadedFile.getBytes();

            Image img = new Image();
            img.setBytes(bytes);
            imageFacadeREST.create(img);

        } catch (Exception e) {
            throw e;
        }
    }
    private int activeLimit;

    public int getActiveLimit() {
        return activeLimit;
    }

    public void setActiveLimit(int activeLimit) {
        this.activeLimit = activeLimit;
    }

    public List<Child> getChildren() {
        return childFacade.findAll().subList(0, activeLimit <= 0 ? childFacade.count() : activeLimit);
    }

    public void setChildren(List<Child> children) {
        this.children = children;
    }
    private List<Child> children;

    public Child getCurrChild() {
        return currChild;
    }

    public void setCurrChild(Child currChild) {
        this.currChild = currChild;
    }

    public Image getCurrImage() {
        return currImage;
    }

    public void setCurrImage(Image currImage) {
        this.currImage = currImage;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<Family> getFamilies() {
        return familyFacade.findAll();
    }

    public List<Child> getChildren(Family family) {
        List<Child> res = childFacade.getChildren(family);
        if (!res.isEmpty()) {
            currChild = res.get(0);
        }
        return res;
    }

    public List<Image> getImages(Family family) {

        if (currChild == null) {
            return new ArrayList<Image>();
        } else {
            List<Image> res = imageFacadeREST.getImages(currChild);
            if (!res.isEmpty()) {
                currImage = res.get(0);
            }
            return res;
        }
    }

    public long getImageId(Family family) {

        getImages(family);
        if (currImage == null) {
            return -1;
        } else {
            return currImage.getId();
        }
    }

    public List<Payment> getPayments() {
        return paymentFacade.findAll();
    }

    
    public List<String> getCurrentChildImages(){
        
        ArrayList<String> res = new ArrayList<String>();
        List<Image> ims = imageFacadeREST.getImages(currChild);
        for (Image im : ims) {
            res.add("/resourcesREST/images/"+im.getId());
        }
        return res;
        
    }
    
    
    
    /** Creates a new instance of PboManagedBean */
    public PboManagedBean() {
    }

    @PostConstruct
    public void init() {

        FacesContext context = FacesContext.getCurrentInstance();
        ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
        path = servletContext.getRealPath("/resources/content");

        Family f = null;
        String[] tmp = {"Kowalscy", "Nowak", "Kiepscy", "Beznadziejni"};
        for (String s : tmp) {
            f = new com.cersoft.xmascharity.entity.Family();
            f.setLastName(s);
            familyFacade.create(f);



            String[] names = {"Ania", "Tomek", "Wiktor", "Eryk"};
            int[] ages = {10, 12, 8, 6};

            File file = new File("obrazek.jpg");

            byte[] bytes = new byte[(int) file.length()];
            try {
                FileInputStream fis = new FileInputStream(file);
                fis.read(bytes);
                fis.close();
            } catch (Exception e) {
            }

            int i = 0;
            for (String s2 : names) {
                Child c = new Child();
                c.setName(s2);
                c.setAge(ages[i++]);
                familyFacade.addChild(f, c);
                Image im = new Image();
                im.setBytes(bytes);
                childFacade.addImage(c, im);
                im = new Image();
                im.setBytes(bytes);
                childFacade.addImage(c, im);
            }
        }

        Payment payment = new Payment();
        payment.setEmail("pbo@dupa.pl");
        payment.setAmount(666.66);
        payment.setRequestDate(new Date());
        paymentFacade.create(payment);

        Payment p2 = payment;

        payment = new Payment();
        payment.setEmail("abc@def.pl");
        payment.setAmount(123.23);
        payment.setRequestDate(new Date());
        paymentFacade.create(payment);

        payment = new Payment();
        payment.setEmail("yrter@uihfd.pl");
        payment.setAmount(34.98);
        payment.setRequestDate(new Date());
        paymentFacade.create(payment);

        p2.setAmount(100.00);
        paymentFacade.edit(p2);

            this.message = paymentFacade.getSum().toString();

    
    }
}
